'use client';

import { useWallet } from '@solana/wallet-adapter-react';
import { useEffect, useState } from 'react';

export function WalletConnectionStatus() {
  const { connecting, connected, wallet, connect, disconnect } = useWallet();
  const [connectionTimeout, setConnectionTimeout] = useState(false);
  const [retryCount, setRetryCount] = useState(0);
  const maxRetries = 3;

  // 连接超时处理
  useEffect(() => {
    let timeout: NodeJS.Timeout;

    if (connecting) {
      // 设置15秒连接超时
      timeout = setTimeout(() => {
        setConnectionTimeout(true);
      }, 15000);
    } else {
      setConnectionTimeout(false);
    }

    return () => {
      if (timeout) {
        clearTimeout(timeout);
      }
    };
  }, [connecting]);

  // 重试连接
  const handleRetry = async () => {
    if (retryCount < maxRetries) {
      setRetryCount(prev => prev + 1);
      setConnectionTimeout(false);
      
      try {
        // 先断开再重连
        if (wallet) {
          await disconnect();
          await new Promise(resolve => setTimeout(resolve, 1000)); // 等待1秒
          await connect();
        }
      } catch (error) {
        console.error('重试连接失败:', error);
      }
    }
  };

  // 重置连接状态
  const handleReset = async () => {
    setRetryCount(0);
    setConnectionTimeout(false);
    try {
      await disconnect();
    } catch (error) {
      console.error('重置连接失败:', error);
    }
  };

  // 如果连接成功，不显示任何内容
  if (connected) {
    return null;
  }

  // 如果正在连接但未超时，显示连接中状态
  if (connecting && !connectionTimeout) {
    return (
      <div className="fixed top-20 right-4 z-50">
        <div className="bg-yellow-500 text-white px-4 py-3 rounded-lg shadow-lg flex items-center space-x-3">
          <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
          <div>
            <div className="font-medium">连接钱包中...</div>
            <div className="text-sm opacity-90">请在 Phantom 钱包中确认连接</div>
          </div>
        </div>
      </div>
    );
  }

  // 如果连接超时或失败，显示错误和重试选项
  if (connectionTimeout || (retryCount > 0 && !connecting)) {
    return (
      <div className="fixed top-20 right-4 z-50">
        <div className="bg-red-500 text-white px-4 py-3 rounded-lg shadow-lg max-w-md">
          <div className="flex items-start justify-between">
            <div className="flex-1">
              <div className="font-medium mb-2">钱包连接超时</div>
              <div className="text-sm opacity-90 mb-3">
                可能的原因：
                <ul className="list-disc list-inside mt-1 text-xs">
                  <li>网络连接不稳定</li>
                  <li>Phantom 钱包未响应</li>
                  <li>RPC 节点繁忙</li>
                </ul>
              </div>
              <div className="flex space-x-2">
                {retryCount < maxRetries && (
                  <button
                    onClick={handleRetry}
                    className="bg-white text-red-500 px-3 py-1 rounded text-sm font-medium hover:bg-gray-100 transition-colors"
                  >
                    重试 ({retryCount + 1}/{maxRetries})
                  </button>
                )}
                <button
                  onClick={handleReset}
                  className="bg-transparent border border-white text-white px-3 py-1 rounded text-sm font-medium hover:bg-white hover:text-red-500 transition-colors"
                >
                  重置
                </button>
              </div>
            </div>
            <button
              onClick={handleReset}
              className="text-white hover:text-gray-200 ml-2"
            >
              ✕
            </button>
          </div>
        </div>
      </div>
    );
  }

  return null;
}
